package main

import (
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/canvas"
	"github.com/flopp/go-findfont"
	"github.com/pelletier/go-toml/v2"
	"go-study-history/gui/fyne_lunbo/entity"
	"go-study-history/gui/fyne_lunbo/resources/utils"
	"image/color"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"
)

const HomeDir = "gui/fyne_lunbo/"
const (
	Icon       = HomeDir + "resources/static/img/carousel-video.png"
	MediaDir   = HomeDir + "resources/media"
	ConfigPath = HomeDir + "resources/config/config.toml"
)

var conf = new(entity.Config)

func init() {
	fontPaths := findfont.List()
	for _, path := range fontPaths {
		if strings.Contains(path, "simkai.ttf") {
			err := os.Setenv("FYNE_FONT", path)
			if err != nil {
				return
			}
			break
		}
	}
	file, err := ioutil.ReadFile(ConfigPath)
	if err != nil {
		log.Fatal("读取配置文件失败", err, "请检查配置文件是否存在！")
	}
	err = toml.Unmarshal(file, conf)
	if conf.ImgFile.Time == 0 {
		conf.ImgFile.Time = 10
	}
	if conf.ImgFile.MediaDir == "" {
		conf.ImgFile.MediaDir = MediaDir
	}
	if conf.WindowAttribute.Width == 0 {
		conf.WindowAttribute.Width = 640
	}
	if conf.WindowAttribute.Height == 0 {
		conf.WindowAttribute.Height = 640
	}
	if conf.WindowAttribute.Title == "" {
		conf.WindowAttribute.Title = "通用轮播软件"
	}
}

func main() {
	//窗口设置
	a := app.New()
	w := a.NewWindow(conf.WindowAttribute.Title)
	iconFile, _ := ioutil.ReadFile(Icon)
	resource := fyne.StaticResource{
		StaticContent: iconFile,
	}
	w.SetFullScreen(false)
	w.SetIcon(&resource)
	//窗口大小
	w.Resize(fyne.NewSize(float32(conf.WindowAttribute.Width), float32(conf.WindowAttribute.Height)))
	//设置播放图片视频容器
	go PlayMedia(w)
	w.ShowAndRun()
}

func PlayMedia(w fyne.Window) {
	dir, err := ioutil.ReadDir(conf.ImgFile.MediaDir)
	if err != nil {
		fmt.Println("读取文件错误！", err)
		return
	}

	fileList := make([]string, 0)
	for _, v := range dir {
		filePath := conf.ImgFile.MediaDir + v.Name()
		filePath, _ = filepath.Abs(filePath)
		contentType := utils.GetFileType(filePath)
		if strings.Contains(contentType, "image") {
			fileList = append(fileList, filePath)
		}
	}
	//提示信息
	if len(fileList) == 0 {
		for {
			time.Sleep(time.Second * 2)
			text := canvas.NewText("未正确配置资源路径，请检查配置", color.White)
			text.Alignment = fyne.TextAlignTrailing
			text.TextStyle = fyne.TextStyle{Italic: true}
			w.SetContent(text)
		}
		//加载图片
	} else {
		num := 0
		for {
			img := canvas.NewImageFromFile(fileList[num])
			img.FillMode = canvas.ImageFillStretch
			w.SetContent(img)
			if num >= len(fileList)-1 {
				num = 0
			} else {
				num += 1
			}
			time.Sleep(time.Second * time.Duration(conf.ImgFile.Time))
		}
	}
}
